package com.example.word2pdf.test;

import org.docx4j.Docx4J;
import org.docx4j.fonts.IdentityPlusMapper;
import org.docx4j.fonts.Mapper;
import org.docx4j.fonts.PhysicalFonts;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;

import java.io.File;
import java.io.OutputStream;
import java.net.URL;

public class Transfer {



    public static void word2Pdf(File word, OutputStream outputStream) throws Exception {
        WordprocessingMLPackage proc= Docx4J.load(word);
        Mapper mapper=new IdentityPlusMapper();
        if(!windows()){
            // linux 下加载字体，目前只加了三种
            String simSun="宋体";
            String msYh="微软雅黑";
            String msYhL="微软雅黑 Light";
            String simSunPath="/usr/local/宋体.tcc";
            String msYhPath="/usr/local/微软雅黑.tcc";
            String msYhLPath="/usr/local/微软雅黑L.tcc";
            URL simSunUrl= new File(simSunPath).toURI().toURL();
            URL msYhUrl= new File(msYhPath).toURI().toURL();
            URL msYhLUrl= new File(msYhLPath).toURI().toURL();
            // 加载字体文件 linux
            PhysicalFonts.addPhysicalFonts(simSun,simSunUrl);
            PhysicalFonts.addPhysicalFonts(msYh,msYhUrl);
            PhysicalFonts.addPhysicalFonts(msYhL,msYhLUrl);
            mapper.put(simSun,PhysicalFonts.get(simSun));
            mapper.put(msYh,PhysicalFonts.get(msYh));
            mapper.put(msYhL,PhysicalFonts.get(msYhL));
        }
        proc.setFontMapper(mapper);
        Docx4J.toPDF(proc,outputStream);
    }

    private static boolean windows() {
        return System.getProperties().getProperty("os.name").toUpperCase().contains("WINDOWS");
    }
}
